package com.sxz.sbs.module.client;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.dialog.input.ValueInputBoardDialog;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.constant.TypeConstant;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.adapter.StallTypeAdapter;
import com.sxz.sbs.module.client.bean.BuildingBean;
import com.sxz.sbs.module.client.bean.ClientBasicBean;
import com.sxz.sbs.module.client.bean.StallRequireBean;
import com.sxz.sbs.module.client.presenter.ClientBasicPresenter;
import com.sxz.sbs.module.client.view.ClientBasicView;
import com.sxz.sbs.module.staff.OperateSuccessActivity;
import com.sxz.sbs.widget.CommonStar;
import com.sxz.sbs.widget.CommonTitle;
import com.willy.ratingbar.BaseRatingBar;
import com.willy.ratingbar.ScaleRatingBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author hp
 * @date 2018/1/11
 * 修改客户基本信息
 */

public class ClientBasicsMsgActivity extends BaseActivity<ClientBasicPresenter> implements ClientBasicView {

    @BindView(R.id.ed_username)
    ClearEditText edUsername;
    @BindView(R.id.ed_phone)
    ClearEditText edPhone;
    @BindView(R.id.ed_phone_2)
    ClearEditText edPhone2;
    @BindView(R.id.ed_phone_3)
    ClearEditText edPhone3;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.ed_buildnum)
    TextView edBuildnum;
    @BindView(R.id.ed_housenumber)
    ClearEditText edHouseNumber;
    @BindView(R.id.ed_annualincome)
    ClearEditText edAnnualincome;
    @BindView(R.id.ed_family)
    ClearEditText edFamily;
    @BindView(R.id.base_msg_car)
    TextView carCount;
    @BindView(R.id.base_msg_stall)
    TextView stallCount;
    @BindView(R.id.et_schedule)
    EditText etSchedule;
    @BindView(R.id.ed_pricemin)
    TextView edPriceMin;
    @BindView(R.id.ed_pricemax)
    TextView edPriceMax;
    @BindView(R.id.recy_stalltype)
    RecyclerView recyStallType;
    @BindView(R.id.clientbasics_ratingbar)
    ScaleRatingBar clientBasics_ratingBar;
    @BindView(R.id.clientbasics_text)
    TextView clientBasicsText;
    @BindView(R.id.tv_amend)
    TextView tvAmend;
    @BindView(R.id.checkbox_intent)
    CheckBox checkBox;
    private Intent intent;
    private ClientBasicBean clientBasicBean;
    private CommonStar commonStar = new CommonStar();
    private List<StallRequireBean> list = new ArrayList<>();
    private StallTypeAdapter stallTypeAdapter;
    private float starNum = 0;
    private int customId;
    private String maxPrice = "", minPrice = "";
    private int buildingId;

    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("基本信息").build().show();
        customId = getIntent().getIntExtra(IntentConstant.CUSTOM_ID, 0);
        getMessage();
        clientBasics_ratingBar.setOnRatingChangeListener(new BaseRatingBar.OnRatingChangeListener() {
            @Override
            public void onRatingChange(BaseRatingBar ratingBar, float rating) {
                starNum = rating;
                commonStar.initStar((int) rating, clientBasicsText);
            }
        });

        recyStallType.setLayoutManager(new GridLayoutManager(this, 4));
        stallTypeAdapter = new StallTypeAdapter(list);
        recyStallType.setAdapter(stallTypeAdapter);
        recyStallType.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (list.get(position).getIsSelect() == 0) {
                    list.get(position).setIsSelect(1);
                } else {
                    list.get(position).setIsSelect(0);
                }
                stallTypeAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新用户信息
        getMessage();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_clientbasicsmsg;
    }

    @Override
    protected ClientBasicPresenter createPresenter() {
        return new ClientBasicPresenter();
    }

    @OnClick({R.id.rela_stallcondition, R.id.rela_havastallmsg, R.id.rela_intention, R.id.tv_amend
            , R.id.ed_buildnum, R.id.ed_pricemin, R.id.ed_pricemax})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            // 选择楼号
            case R.id.ed_buildnum:
                if (clientBasicBean == null) {
                    return;
                }
                startActivityForResult(new Intent(this, BuildingNumberActivity.class)
                                .putExtra("parking_id", clientBasicBean.getParking_Id())
                        , 1004);
                break;
            // 车辆情况
            case R.id.rela_stallcondition:
                intent = new Intent(ClientBasicsMsgActivity.this, CarListActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, customId);
                startActivity(intent);
                break;
            case R.id.rela_havastallmsg:
                intent = new Intent(ClientBasicsMsgActivity.this, StallListActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, customId);
                startActivity(intent);
                break;
            case R.id.rela_intention:
                if (clientBasicBean == null) {
                    return;
                }
                intent = new Intent(ClientBasicsMsgActivity.this, IntentionStallActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, customId);
                intent.putExtra("parking_id", clientBasicBean.getParking_Id());
                startActivity(intent);
                break;
            case R.id.ed_pricemin:
                ValueInputBoardDialog dialog2 = new ValueInputBoardDialog(this, minPrice, ValueInputBoardDialog.UnitEnum.SELL);
                dialog2.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        minPrice = value;
                        edPriceMin.setText(value + unit);
                    }
                });
                dialog2.show();
                break;
            case R.id.ed_pricemax:
                ValueInputBoardDialog dialog3 = new ValueInputBoardDialog(this, maxPrice, ValueInputBoardDialog.UnitEnum.SELL);
                dialog3.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        maxPrice = value;
                        edPriceMax.setText(value + unit);
                    }
                });
                dialog3.show();
                break;
            case R.id.tv_amend:
                getSubmitMessage();
                break;
            default:
                break;
        }
    }


    @Override
    public void onEssentialInformationSuccess(ClientBasicBean data) {
        if (mIsLive && data != null) {
            clientBasicBean = data;
            buildingId = data.getBuild_Id();
            edUsername.setText(data.getTxt_UserName());
            String[] phoneArr = data.getTxt_Phone().split(",");
            switch (phoneArr.length) {
                case 1:
                    edPhone.setText(phoneArr[0]);
                    break;
                case 2:
                    edPhone.setText(phoneArr[0]);
                    edPhone2.setText(phoneArr[1]);
                    break;
                case 3:
                    edPhone.setText(phoneArr[0]);
                    edPhone2.setText(phoneArr[1]);
                    edPhone3.setText(phoneArr[2]);
                    break;
                default:
                    edPhone.setText(phoneArr[0]);
                    break;
            }

            edBuildnum.setText(data.getTxt_BuildNum());
            String sex = "男";
            if (sex.equals(data.getTxt_Sex())) {
                radioGroup.check(R.id.man);
            } else {
                radioGroup.check(R.id.rb_woman);
            }

            list.clear();
            String json = data.getTxt_IntentLabel();
            List<StallRequireBean> benList = new Gson().fromJson(json, new TypeToken<List<StallRequireBean>>() {
            }.getType());
            list.addAll(benList);
            stallTypeAdapter.notifyDataSetChanged();
            edBuildnum.setText(data.getTxt_BuildNum());
            edHouseNumber.setText(data.getAddr_Address());
            edAnnualincome.setText(data.getTxt_Income());
            edFamily.setText(data.getTxt_FamilyInfo());
            carCount.setText(data.getCarCount() + "");
            stallCount.setText(data.getSpaceCount() + "");
            edPriceMin.setText(data.getVal_PriceMin() + "元");
            edPriceMax.setText(data.getVal_PriceMax() + "元");
            minPrice = data.getVal_PriceMin() + "";
            maxPrice = data.getVal_PriceMax() + "";
            clientBasics_ratingBar.setRating(data.getVal_StarLevel());
            if (data.getVal_Type() == TypeConstant.VAL_TYPE_HAVE) {
                checkBox.setChecked(true);
            }
        }

    }

    @Override
    public void onClientAmendSuccess(String data) {
        startActivity(OperateSuccessActivity.class);
        finish();
    }

    /**
     * 获取客户基本信息
     */
    private void getMessage() {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", customId);
        mPresenter.getClientBasic(map);
    }

    /**
     * 提交修改信息
     */
    private void getSubmitMessage() {
        /**
         a.Id	int	否	客户ID
         a.Build_Id	int	是	楼号ID
         a.Parking_Id	int	是	所属小区ID
         a.txt_UserName	string	是	客户姓名
         a.txt_Phone	string	是	客户电话
         a.txt_Sex	string	否	性别
         a.addr_Address	string	否	详细住址，到门牌号
         a.txt_Income	string	否	年收入
         a.txt_FamilyInfo	string	否	家庭情况
         a.val_PriceMin	int	否	意向车位价格区间下限（价格上下限要么都传，要么都不传）
         a.val_PriceMax	int	否	意向车位价格区间上限（价格上下限要么都传，要么都不传）
         a.val_StarLevel	int	否	客户意向星级
         a.txt_IntentLabel	string	否	客户意向标签（使用 | 拼接每一个选中的标签传入）
         b.txt_Content	string	否	跟进记录
         isIntent	int	是	是否是意向客户 （1、普通客户 2、加入到意向客户）
         */
        if (clientBasicBean == null) {
            return;
        }
        if (TextUtils.isEmpty(edUsername.getInputValue())) {
            ToastUtils.showShort("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(edPhone.getInputValue()) && TextUtils.isEmpty(edPhone2.getInputValue())
                && TextUtils.isEmpty(edPhone3.getInputValue())) {
            ToastUtils.showShort("手机号不能为空");
            return;
        }
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("a.Id", customId);
        map.put("a.Build_Id", buildingId);
        map.put("a.Parking_Id", clientBasicBean.getParking_Id());
        map.put("a.txt_UserName", edUsername.getInputValue());
        String phone = "";
        if (!TextUtils.isEmpty(edPhone.getInputValue())) {
            phone = phone + edPhone.getInputValue() + ",";
        }
        if (!TextUtils.isEmpty(edPhone2.getInputValue())) {
            phone = phone + edPhone2.getInputValue() + ",";
        }
        if (!TextUtils.isEmpty(edPhone3.getInputValue())) {
            phone = phone + edPhone3.getInputValue() + ",";
        }
        phone = phone.substring(0, phone.length() - 1);
        map.put("a.txt_Phone", phone);
        map.put("a.txt_Sex", radioGroup.getCheckedRadioButtonId() == R.id.man ? "男" : "女");
        map.put("a.addr_Address", edHouseNumber.getInputValue());
        map.put("a.txt_Income", edAnnualincome.getInputValue());
        map.put("a.txt_FamilyInfo", edFamily.getInputValue());
        map.put("a.val_PriceMin", minPrice);
        map.put("a.val_PriceMax", maxPrice);
        map.put("valStarLevel", (int) starNum);
        String lebal = "";
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getIsSelect() == 1) {
                lebal = lebal + list.get(i).getIntentWord() + "|";
            }
        }
        if (!TextUtils.isEmpty(lebal)) {
            lebal = lebal.substring(0, lebal.length() - 1);
        }
        map.put("a.txt_IntentLabel", lebal);
        map.put("b.txt_Content", etSchedule.getText().toString());
        map.put("isIntent", checkBox.isChecked() ? 2 : 1);

        mPresenter.getAmendClient(map);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == 1004) {
            BuildingBean.ListBean bean = data.getParcelableExtra("building_result");
            if (bean != null) {
                buildingId = bean.getId();
                edBuildnum.setText(bean.getTxt_BuildNum());
            }
        }
    }
}
